<?php
/**
 * Created by LíJimpéy(：
 * User: jimpey88
 * Date: 2024/3/28
 * Email: < jimpey@qq.com >
 * Project: company-admin-tp6
 */

namespace app\backend_api\services;

use app\backend_api\exception\AdminApiException;
use app\backend_api\model\AdminMenus;
use app\backend_api\model\AdminRoles;
use app\backend_api\model\AdminUsers;
use app\common\Utils\IpInfoUtils;
use Psr\SimpleCache\InvalidArgumentException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;

class LoginService
{

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws InvalidArgumentException
     */
    public function login($params)
    {
        $admin = AdminUsers::where('name', $params['name'])->find();
        if (!$admin) {
            throw new AdminApiException('用户名不存在');
        }
        if ($admin->status != 1) {
            throw new AdminApiException('用户状态异常');
        }
        if (!password_verify($params['password'], $admin->password)) {
            throw new AdminApiException('账号或密码错误，请重新输入');
        }

        //用户表登录信息更新
        $admin->last_login_at = date('Y-m-d H:i:s');
        $admin->last_login_ip = IpInfoUtils::info()['ip'];
        $admin->save();

        //设置token
        $tokenInfo = JwtTokenService::generateToken($admin->id);

        // 设置登录redis缓存标识
        Cache::store('redis')->set('admin_id_' . $admin->id, $tokenInfo['token'], (int)env('jwt.exp'));

        //返回登录信息
        return [
            'access_token' => $tokenInfo['token'],
            'token_type' => 'bearer',
            'expires_in' => $tokenInfo['expires_in']
        ];
    }

    public static function getAdminInfo(): array
    {
        $admin = AdminUsers::find(request()->admin_id);
        // 如果是is_super = 1超管，那么默认返回全部权限
        if($admin['is_super'] === 1){
            $admin = $admin->toArray();
            $admin['role_names'] = ['超级管理员'];
            $admin['authorityRouter'] = list_to_tree(AdminMenus::select()->toArray());
            return $admin;
        }

        $adminRole = $admin->roles;
        if ($adminRole->isEmpty()) {
            throw new AdminApiException('用户未配置角色');
        }

        $menus = [];
        $slugs = [];
        // 遍历每个角色,获取对应的菜单
        foreach ($adminRole as $role) {
            foreach ($role->menus as $menu) {
                $slugs[] = $menu->slug;
                $menus[] = $menu->toArray(); // 将 Menu 模型转换为数组
            }
        }
        $roleArray = $adminRole->toArray();
        $admin = $admin->toArray();
        unset($admin['roles']);
        $admin['role_id'] = array_column($roleArray, 'id');
        $admin['role_names'] = array_column($roleArray, 'role_name');
        $admin['authorityRouter'] = list_to_tree($menus);
        $admin['permissionButton'] = array_values(array_filter($slugs));

        return $admin;
    }

}